package com.sj.purchase.util;

import com.sj.purchase.common.utils.FileOperateUtil;
import com.sj.purchase.exception.SanJiException;
import com.sj.purchase.util.excel.ExcelUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by yangrd on 2017/7/27.
 */
public final class ExcelDownloadUtil {

    private ExcelDownloadUtil() {

    }

    /**
     * 使用easyPoi下载
     */
    public static <T> void easyPoi(String name, Class<T> t, List<T> content) {
        download(name, ExcelExportUtil.exportExcel(new ExportParams(), t, content));
    }

    /**
     * 使用我们自己分装的
     */
    public static <T> void exportExcel(String name, Class<T> t, List<T> content) {
        download(name, new ExcelUtil<>(t).exportExcel(content, name));
    }

    /**
     * 共有的
     */
    public static void download(String name, Workbook workbook) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            FileOperateUtil.download(request, response, name + ".xls", workbook);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SanJiException("excel 导出失败");
        }
    }
}
